<?php
namespace common\helpers\Uploads;

/**
 * 七牛云安装 composer require qiniu/php-sdk 7.4
 * Class QiuniuApi
 * @package common\helpers\Uploads
 */

use common\helpers\commonApi;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
class QiuniuApi implements Upload
{
    private $accesskey = null;//七牛云ak
    private $secretkey = null;//七牛云sk
    private $bucket = null;//空间
    private $auth = null;//
    private $domain = null;//域名

    public function __construct($accesskey, $secretkey, $bucket,$domain)
    {
        $this->accesskey = $accesskey;
        $this->secretkey = $secretkey;
        $this->bucket = $bucket;
        $this->domain = $domain;
        if (!$this->auth){
            $this->auth = new Auth($accesskey, $secretkey);
        }
    }

    /**
     * @param $filePath
     * @param $fileName
     * @return bool
     */
    public function uploadFile(string $filePath,string $fileName)
    {
        // 生成上传 Token
        $token = $this->auth->uploadToken($this->bucket);
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $fileName, $filePath);
        if ($err !== null) {
            return commonApi::message('上传七牛云失败！',false);
        } else {
            return commonApi::message('ok',true,['url'=>$this->domain.'/'.$ret['key']]);
        }
    }

    public function delete(string $filePath)
    {
        $pathinfo = pathinfo($filePath);
        if (empty($pathinfo['basename'])){
            return commonApi::message('文件不正确',false);
        }
        $config = new \Qiniu\Config();
        $bucketManager = new BucketManager($this->auth, $config);
        $err = $bucketManager->delete($this->bucket, $pathinfo['basename']);
        if (empty($err[0]) && empty($err[1])) {
            return commonApi::message('删除成功');
        }
        return commonApi::message('删除失败', false);
    }

    public function deleteAll(array $filePaths)
    {
        $success = 0;
        $fail = 0;
        $fail_data = [];
        $success_data = [];
        foreach ($filePaths as $filePath){
            $res = $this->delete($filePath);
            if ($res['success']){
                $success += 1;
                $success_data[] = $filePath;
            }else{
                $fail += 1;
                $fail_data[] = $filePath;
            }
        }
        return commonApi::message("删除失败：成功{$success}条，失败{$fail}条", true, ['success' => $success_data, 'fail' => $success_data]);
    }
}